package html.util;
import js.Lib;
import oboe.core.SigSlot;
import js.Dom;

/**
 * ...
 * @author Felipe Manga
 */

class Container extends SigSlot
{
	private var element:HtmlDom;
	private var displayMode:String;
	private var formStack:Array<Form>;
	private var forms:Dynamic;
	public var defaultVisible:Bool;
	public var visible( default, setVisible ):Bool;
	
	public function new( id:String="" ) 
	{
		super();
		if ( id == "" )
		{
			id = Type.getClassName(Type.getClass(this)).toLowerCase().split(".").pop();
		}
		
		defaultVisible = true;
		
		this.element = Lib.document.getElementById(id);
		if ( this.element != null )
		{
			this.displayMode = this.element.style.display;
		}
		
		this.hide();
		this.forms = { };
		this.formStack = new Array<Form>();
		setupForms( );
	}
	
	private function setVisible( v:Bool ):Bool
	{
		this.visible = v;
		if ( v ) this.show();
		else this.hide();
		return v;
	}
	
	private function setupForms()
	{
		for ( fnum in 0 ... Lib.document.forms.length )
		{
			var form:Form = Lib.document.forms[fnum];
			var p:Dynamic = form.parentNode;
			if ( !StringTools.startsWith(form.action, "sig:") ) continue;
			
			while ( p != this.element && p != null ) p = p.parentNode;
			if ( p == null ) continue;
			
			form.onsubmit = onSubmitForm;
		}
	}
	
	private function onSubmitForm( event:js.Event ):Bool
	{
		if ( event == null ) event = untyped Lib.window.event; // IE hack. Thank you, Microsoft.
		
		var e:Array<String> = [];
		
		var form:Form = cast event.target;
		if ( form == null ) form = untyped event.srcElement; // Yet another IE hack. They should call it Stupidsoft.
		
		for ( f in 0 ... form.elements.length )
		{
			if ( form.elements[f].name != "" )
			{
				e.push( form.elements[f].value );
			}
		}
		
		this.message( "server_" + (form.action.split(":")[1]), e ); 
		return false; 		
	}
	
	private function get( id:String ):Dynamic
	{
		return Lib.document.getElementById( this.element.id + "." + id );
	}
	
	@slot override function onAddToParent():Void
	{
		super.onAddToParent();
		if ( this.defaultVisible ) this.show();
		else this.hide();
	}
	
	@slot function onExitState():Void
	{
		this.hide();
	}
	
	@slot function show():Void
	{
		if ( this.element != null )
		{
			this.element.style.display = this.displayMode;
		}
		this.visible = true;
	}
	
	@slot function hide():Void
	{
		if ( this.element != null )
		{
			this.element.style.display = "none";
		}
		this.visible = false;
	}
}